package com.fcbox.bypass.redis.serializer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.BeforeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

/**
 * fastJson序列化类
 * Created by 000498 on 2017/5/12.
 */
public class Fastjson2JsonRedisSerializer<T> implements RedisSerializer<T> {
	public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

	private Class<T> clazz;

	public Fastjson2JsonRedisSerializer(){
	}

	public Fastjson2JsonRedisSerializer(Class<T> clazz) {
		super();
		this.clazz = clazz;
	}

	public byte[] serialize(T t) throws SerializationException {
		if (t == null) {
			return new byte[0];
		}
		return JSON.toJSONString(t,new TimeStampFilter(), SerializerFeature.WriteClassName, SerializerFeature.WriteDateUseDateFormat).getBytes(DEFAULT_CHARSET);
	}

	public T deserialize(byte[] bytes) throws SerializationException {
		if (bytes == null || bytes.length <= 0) {
			return null;
		}
		String str = new String(bytes, DEFAULT_CHARSET);

		return JSON.parseObject(str, this.clazz);
	}

	/**
	 * 为redis序列化的字符串添加时间戳
	 * Created by 000498 on 2016/12/24.
	 */
	private class TimeStampFilter extends BeforeFilter {
		@Override
		public void writeBefore(Object object) {
			writeKeyValue("@serialTm", System.currentTimeMillis());
		}
	}
}
